package dotdashdot.bradz.trendsettr;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

//Adapter for the old SeeTrends Activity. Deprecated. See ClassTrendsettrAdapterAlt and ActivityItemDetail/List
public class ClassTrendsettrAdapter extends SimpleAdapter implements Filterable{

	int resource;
	Context context;
	ClassFonts fonts;
	List<? extends HashMap<String, ?>> data;
	String[] from;
	int[] to;
	boolean filter_opinions;
	PositionClicked click;
	ClassFilterPopup info_popup;
	final Object mLock = new Object();
	ItemsFilter mFilter;
	ArrayList<HashMap<String, String>> mItems;
	
	public ClassTrendsettrAdapter(Context context,
			List<? extends HashMap<String, ?>> data, int resource, String[] from,
			int[] to, ClassFonts fonts, ClassFilterPopup info_popup) {
		super(context, data, resource, from, to);
		this.resource = resource;
		this.context = context;
		this.fonts = fonts; 
		this.data = data;
		this.from = from;
		this.to = to;
		filter_opinions = false;
		click = new PositionClicked();
		this.info_popup = info_popup;
		// TODO Auto-generated constructor stub
	}

	@Override
    public View getView(int position, View v, ViewGroup parent)
    {
        View mView = super.getView(position, v, parent);
        
        //These statements control if the toolbar is expanded or not when the list is moved up and down
        //Since mView wont be null anymore...
        Log.i("TrendAdapter","TrendAdapter - clicked: " + click.clicked);
    	Log.i("TrendAdapter","TrendAdapter - position: " + position);
        if(click.clicked != position){
        	//To prevent the visibility from being recycled
        	View expandable = mView.findViewById(R.id.toolbar);
        	if(expandable.getVisibility()!=View.GONE){
            	Log.i("TrendAdapter","TrendAdapter - close");
        		expandable.setVisibility(View.GONE);
        	}
        }else{
        	//This expands the selected view
        	View expandable = mView.findViewById(R.id.toolbar);
        	if(expandable.getVisibility()!=View.VISIBLE){
        		Log.i("TrendAdapter","TrendAdapter - open");
        		click.populate_view(expandable);
                // Creating the expand animation for the item
        		ClassExpandAnimation expandAni = new ClassExpandAnimation(expandable, 500);
                // Start the animation on the toolbar
                expandable.startAnimation(expandAni);
        	}
        }
        /*if(mView == null){
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mView = vi.inflate(resource, null);*/
        	
        	//View details = mView.findViewById(R.id.toolbar);
        Map<String, ?> map = (HashMap<String,?>) getItem(position);
		//if(info_popup.get_checked_filters().contains(String.valueOf(map.get("Topic")))){
	        /*for (Map.Entry<String, ?> entry : map.entrySet()) {
	            System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
	        }*/
	        View details = (View) mView.findViewById(R.id.text_holder);
	        if(filter_opinions){
			   if(Integer.valueOf(String.valueOf(map.get("Voted")))==1){
				   details.setBackgroundColor(context.getResources().getColor(R.color.list_green));
			   }else{
				   details.setBackgroundColor(context.getResources().getColor(R.color.list_red));
			   }
		   }else{
			   details.setBackgroundColor(context.getResources().getColor(R.color.list_white));
		   }
	        TextView column;
	        int count = 0;
	        //for(int i = 0; i < map.entrySet().size();i++){
	        for (int i = 0; i < to.length; i++) {
	        	column = (TextView) mView.findViewById(to[count]);
	        	if(column != null){
	            	Log.i("List","Value: " + map.get(from[i]));
	            	column.setText(String.valueOf(map.get(from[i])));
	            	column.setTypeface(fonts.get_font("bold"));
	        	}else{
	        		Log.i("List","Column null!!!");
	        	}
	        	count++;
	        }
		//}
        //}
		return mView;
    }
	
	public void set_click(int click_position){
		Log.i("ClassTrendAdapter","Click Position: " + click_position);
		Log.i("ClassTrendAdapter","Previous Click Clicked: " + click.clicked);
		
		//Make sure that the animation has ended before changing the click pattern

		if(click.clicked == -1 || click.clicked != click_position){
			click.clicked = click_position;
		}else{
			click.clicked = -1;
		}		//Log.i("ClassTrendAdapter","Click Clicked: " + click.clicked);
		
		//Make sure that the listview know something has happened...
		//notifyDataSetChanged();
	}
	
	public int get_click(){
		return click.clicked;
	}
	
	public void set_graph_info(XYSeries toolbar_series, String trend_name, String meta_summary, int color){
		click.set_graph_info(toolbar_series, trend_name, meta_summary, color);
	}
	
	
	public void filter_opinions(boolean filter_opinions){
		this.filter_opinions = filter_opinions;
		Log.i("TrendSettrAdapter","FilterOpinions: " + this.filter_opinions);
	}
	
	private static class PositionClicked {
	    public int clicked;
	    public String trend_name, meta_summary;
	    public XYSeries toolbar_series;
	    public int color;
	    PositionClicked(){
		    clicked = -1;
		    trend_name = "";
		    toolbar_series = null;
		    color = 0;
	    }
	    public void set_graph_info(XYSeries toolbar_series, String trend_name, String meta_summary, int color){
			this.toolbar_series = toolbar_series;
			this.trend_name = trend_name;
			this.meta_summary = meta_summary;
			this.color = color;
		}
	    public void populate_view(View v){
	    	XYPlot dynamic_plot = (XYPlot) v.findViewById(R.id.trend_plot);
	        
	        /*ClassFormatGraph formatter = */
	    	new ClassFormatGraph(dynamic_plot, toolbar_series, color);
	        
	        //Format the graph here with the stuff that we want
	        //dynamic_plot = formatter.get_graph();

	        TextView item_details = (TextView) v.findViewById(R.id.see_trend_details);
	        item_details.setText(trend_name + ": " + meta_summary);
	        
	        //dynamic_plot = formatter.get_graph();
	        
	    }
	}
	
	private class ItemsFilter extends Filter {
		protected FilterResults performFiltering(CharSequence prefix) {
            // Initiate our results object
            FilterResults results = new FilterResults();
            // If the adapter array is empty, check the actual items array and use it
            if (mItems == null) {
                synchronized (mLock) { // Notice the declaration above
                    mItems = new ArrayList<HashMap<String,String>>();
                }
            }
            // No prefix is sent to filter by so we're going to send back the original array
            if (prefix == null || prefix.length() == 0) {
                synchronized (mLock) {
                    results.values = data;
                    results.count = data.size();
                }
            } else {
            	
            	ArrayList<HashMap<String,?>> newItems = new ArrayList<HashMap<String,?>>();
            	for(HashMap<String, ?> item: data){
            		if(info_popup.get_checked_filters().contains(item.get("Topic"))){
            			newItems.add(item);
            		}
            	}
                // Set and return
                results.values = newItems;
                results.count = newItems.size();
            }
            return results;
        }
        @SuppressWarnings("unchecked")
        protected void publishResults(CharSequence prefix, FilterResults results) {
            //noinspection unchecked
            mItems = (ArrayList<HashMap<String, String>>) results.values;
            // Let the adapter know about the updated list
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
	}
	
	@Override
	public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new ItemsFilter();
        }
        return mFilter;
	}
	
}
